<?php

namespace App\Models\Common;

use App\Models\BaseModel;

class OperationLog extends BaseModel
{

    /**
     * 操作日志数据表名
     *
     * @var string
     */
    protected $table = 'operation_logs';

    /**
     * 可以被集体附值的表的字段
     *
     * @var string
     */
    protected $fillable = array('id', 'user_id', 'method', 'ip', 'path', 'type', 'description', 'params', 'agent_model', 'client', 'browser', 'data_scope');
    public $sorters = ['method', 'browser', 'client', 'ip', 'created_at'];

    public function user()
    {
        return $this->belongsTo('App\Models\Account\User', 'user_id');
    }

    /**
     * 增加操作日志
     *
     * @param array $data 所需要插入的信息
     */
    public function add(array $data)
    {
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    /**
     * 获取log日志内容
     * @param $limit    分页限制条数
     * @param $sorter   排序
     * @param $search   查询
     * @return mixed
     */
    public function getLogList($limit, $sorter, $search)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;

        $model = $this->with(['user:id,username'])->orderBy($sorter[0], $sorter[1]);

        if (!empty($search['username'])) {
            $model = $this->whereHas('user', function ($query) use ($search) {
                        $query->where('username', 'like', '%' . $search['username'] . '%');
                    })->with(['user:id,username']);
        }

        if (!empty($search['start_time'])) {
            $model->where('created_at', '>=', $search['start_time']);
        }

        if (!empty($search['end_time'])) {
            $model->where('created_at', '<=', $search['end_time']);
        }

        return $model->paginate($perPage)->toArray();
    }

}
